/*
* @Author: zhangsai
* @Date: 2018/4/24
* @description:  logo
*/
<template>
  <div>
    <div class="logo-img" @click="dialogVisible=true">
      <el-upload
        ref="uploadLogo"
        class="avatar-uploader"
        action=""
        :show-file-list="false"
        :http-request="myUpload"
        :disabled="true"
        >
        <img v-if="src && !imageUrl" :src="src" class="avatar">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-if="!src && !imageUrl" class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <el-dialog title="裁剪logo"
      :visible.sync="dialogVisible"
      width="50%"
      :append-to-body='true'>
      <div class="ex-img-box">
        <vueCropper
                ref="cropper"
                :img="exImg"
                :autoCrop="true"
                :autoCropWidth="200"
                :autoCropHeight="200"
                :fixedBox="false"
                :fixed="true"
                :fixedNumber="[1, 1]"
                outputType="png">
        </vueCropper>
      </div>
      <div class="m-t-15 align-right">  
        <el-button type="primary" class="m-r-10" round><label class="btn" for="uploads">选择图片</label></el-button>
        <input type="file" 
                id="uploads" 
                style="position:absolute; clip:rect(0 0 0 0);" 
                accept="image/png, image/jpeg, image/gif, image/jpg" 
                @change="uploadImg($event, 1)" />
        <el-button type="primary" @click="finish" round>确定</el-button>  
      </div>       
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
import BaseService from '../../service/common';
import API from '../../service/common/api';
import { csHttpUploadFile } from '../../service/formData';
import vueCropper from 'vue-cropper';
import uuidv1 from 'uuid';
interface Policy {
  key: string;
  dir: string;
  policy: string;
  accessid: string;
  success_action_status: string;
  callback: string;
  signature: string;
  file: any;
}
@Component({
  components: {
    'vueCropper': vueCropper
  }
})
export default class LogoImg extends Vue {
  @Prop({ default: null })
  public src: string|null;
  // 初始化数据 相当于data
  public imageUrl = '';
  // refs
  public $refs: {
    cropper: HTMLFormElement,
    uploadLogo: HTMLFormElement
  };
  // 弹框开关
  public dialogVisible = false;
  // 显示 imgurl
  public exImg = '';
  // 授权 对象
  public policy = {} as Policy;
  // 选择的图片
  public file: {name?: string} = {};
  // 裁剪后的图片
  public finishFile: {name?: string} = {};
  // 方法
  public async mounted() {
    const policy = await BaseService.getPolicy();
    this.policy = JSON.parse(policy);
  }
  // 剪切
  public finish() {
    this.dialogVisible = false;
    // this.$refs.cropper.getCropBlob((data: any) => {
    //   console.log(data, 'data');
    //   this.finishFile = data;
    //   this.imageUrl = window.URL.createObjectURL(data);
    //   console.log(this.imageUrl, 'this.imageUrl');
    // });
    this.$refs.cropper.getCropData((data) => {
      // do something
      this.imageUrl = data;
      if (this.file.name) {
        const pList = this.file.name.split('.');
        const p = pList[pList.length - 1];
        const name = uuidv1() + '.' + p;
        this.finishFile = this.dataURLtoFile(data, name);
      }
    });
  }
  // 选择图片
  public uploadImg(e: any) {
    const file = e.target.files[0];
    const target: any = e.target;
    if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        this.$message.warning('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
        return;
    }
    if (file.size / 1024 > 2000) {
      this.$message.warning('图片大小不能超过2M！');
        return;
    }
    this.file = file;
    const reader = new FileReader();
    reader.onload = (event) => {
      let data;
      const eventTarget: any = event.target;
      if (typeof eventTarget.result === 'object') {
        // 把Array Buffer转化为blob 如果是base64不需要
        data = window.URL.createObjectURL(new Blob([eventTarget.result]));
      } else {
        data = target.result;
      }
      this.exImg = data;
    };
    // 转化为base64
    // reader.readAsDataURL(file)
    // 转化为blob
    reader.readAsArrayBuffer(file);  
  }
  // 自定义上传
  public async myUpload() {
    if (this.finishFile.name) {
      const xhrStatusText = await csHttpUploadFile(API.UPLOAD_URL.url, {}, Object.assign({}, {
                key: this.policy.dir + '${filename}',
                policy: this.policy.policy,
                OSSAccessKeyId: this.policy.accessid,
                success_action_status: '200',
                callback: this.policy.callback,
                signature: this.policy.signature,
                file: [this.finishFile]
            }), true);
            if (xhrStatusText === 'OK') {
              this.$emit('onSuccess', this.policy.dir + this.finishFile.name);
            } else {
              this.$message.warning('上传logo失败！');
            }       
    } else {
      this.$emit('onSuccess', null);
    }
  }
  public up() {
    this.myUpload();
  }
  // base64转file对象
  public dataURLtoFile(dataurl: any, filename: string) {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]); 
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type: mime});
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.logo-img{
  display:inline-block;
}
.ex-img-box{
  margin:0 auto;
  width:100%;
  height:400px;
}
.m-r-10{
  margin-right:10px;
}
</style>
